package com.ltsznh.android.familybooks;

import android.app.ActionBar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.ltsznh.android.familybooks.db.dbo;
import com.ltsznh.android.familybooks.record.EditRecordActivity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

public class BlottersActivity extends Activity {

    protected String invType = "O";
    protected String invDate;
    protected EditText dateEditText;

    protected ListView blottersListView;
    private ArrayList<HashMap<String, Object>> listItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blotters);

        ActionBar actionBar = this.getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
//        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
//        //生成一个spinneradaper，设置actionbar下拉菜单的菜单项
//        SpinnerAdapter spinnerAdapter = ArrayAdapter.createFromResource(this, R.array.action_bar_blotters_list_category, android.R.layout.simple_spinner_dropdown_item);
//        //为actionbar设置适配器跟监听器
//        actionBar.setListNavigationCallbacks(spinnerAdapter,new DropDownListener());


        blottersListView = (ListView) findViewById(R.id.listView_blotters_blotters);
        listItem = new ArrayList<HashMap<String, Object>>();

        dateEditText = (EditText) findViewById(R.id.editText_blotters_date);

        initDate();
    }

    @Override
    protected void onStart() {
        super.onStart();
        refreshData();
    }

    private void initDate() {
        invDate = getIntent().getStringExtra("invDate");
        dateEditText.setText(invDate);

        refreshData();
    }

    public void selectDate(View view){
        int id = view.getId();
        final Calendar invCalendar = Calendar.getInstance();
        switch (id){
            case R.id.editText_blotters_date:
                DatePickerDialog.OnDateSetListener test = new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int year, int month, int day) {
                        invCalendar.set(year,month,day);
                        invDate = MainActivity.format.format(invCalendar.getTime());
                        dateEditText.setText(invDate);
                        refreshData();
                    }
                };

                DatePickerDialog invDatePicker;
                invDatePicker = new DatePickerDialog(this,test,Integer.parseInt(invDate.substring(0,4)),
                        Integer.parseInt(invDate.substring(5,7)) - 1,Integer.parseInt(invDate.substring(8,10)));
                invDatePicker.show();
                return;
            case R.id.button_blotters_left:
                invCalendar.set(Integer.parseInt(invDate.substring(0,4)),
                        Integer.parseInt(invDate.substring(5,7)) - 1,Integer.parseInt(invDate.substring(8,10)) - 1);
                break;
            case R.id.button_blotters_right:
                invCalendar.set(Integer.parseInt(invDate.substring(0,4)),
                        Integer.parseInt(invDate.substring(5,7)) - 1,Integer.parseInt(invDate.substring(8,10)) + 1);
                break;
            default:
                return;
        }
        invDate = MainActivity.format.format(invCalendar.getTime());
        dateEditText.setText(invDate);
        refreshData();
    }

    protected void refreshData(){
        String sqlString = "select id,invDate,entryTime,invPicture,(case invType when 'I' then yuan else '' end) as inYuan ," +
                "(case invType when 'O' then yuan else '' end) as outYuan ," +
                "invType,invCategory,invCategory2,accountCategory,account,remark,isInvalid,place," +
                "longitude,latitude,accuracy,placeTime " +
                "from inv_blotters where invType = ? and invDate =? order by invDate,entryTime";
        Log.d(this.getLocalClassName(),sqlString + invType);
        dbo.getReadableDatabase(this);
        Cursor blottersCursor =  dbo.fbSQLite.rawQuery(sqlString,new String[]{invType,invDate});
        listItem.clear();
        if(blottersCursor.getCount() > 0){
            HashMap<String, Object> blottersMap;
            blottersCursor.moveToFirst();
            do{
                blottersMap = new HashMap<String, Object>();
                blottersMap.put("id",blottersCursor.getInt(blottersCursor.getColumnIndex("id")));
//                blottersMap.put("invPicture", blottersCursor.getBlob(blottersCursor.getColumnIndex("invPicture")));
//                blottersMap.put("invPicture", android.R.drawable.ic_menu_gallery);
                blottersMap.put("invDate", blottersCursor.getString(blottersCursor.getColumnIndex("invDate")));
                blottersMap.put("inYuan",blottersCursor.getString(blottersCursor.getColumnIndex("inYuan")));
                blottersMap.put("outYuan",blottersCursor.getString(blottersCursor.getColumnIndex("outYuan")));
                blottersMap.put("category", blottersCursor.getString(blottersCursor.getColumnIndex("invCategory")) + " > " + blottersCursor.getString(blottersCursor.getColumnIndex("invCategory2")));
                blottersMap.put("account", blottersCursor.getString(blottersCursor.getColumnIndex("accountCategory")) + " > " + blottersCursor.getString(blottersCursor.getColumnIndex("account")));
                listItem.add(blottersMap);
            }while (blottersCursor.moveToNext());
        }
        //生成适配器的Item和动态数组对应的元素
        SimpleAdapter blottersListItemAdapter = new SimpleAdapter(this,listItem, R.layout.blotters_item,
                new String[] {"invPicture","invDate", "category","account","inYuan","outYuan"},
                new int[] {R.id.imageView_blotters_item_picture,R.id.textView_blotters_item_day,
                        R.id.textView_blotters_item_category,R.id.textView_blotters_item_account,
                        R.id.textView_blotters_item_in,R.id.textView_blotters_item_out}
        );

        blottersListView.setAdapter(blottersListItemAdapter);

        blottersListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                HashMap<String, Object> selectedItem = listItem.get(i);
                Intent intent = new Intent();
                intent.setClass(BlottersActivity.this, EditRecordActivity.class);
                intent.putExtra("id", (Integer) selectedItem.get("id"));
                intent.putExtra("invType", invType);
//                Log.d(this.getClass().getName(), (Integer) selectedItem.get("id") + "/" );
                startActivity(intent);
                return false;
            }
        });
    }

    protected void goHome(){
        Log.d(this.getClass().toString(),  "to home");
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()){
            case android.R.id.home:
                goHome();
                return true;
            case R.id.action_in:
                invType = "I";
                refreshData();
                Log.d(this.getClass().toString(), "action in");
                return true;
            case R.id.action_out:
                invType = "O";
                refreshData();
                Log.d(this.getClass().toString(), "action out");
                return true;
            default:
                Log.d(this.getClass().toString(),"nothing");
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.blotters, menu);
        return true;
    }

//    private class DropDownListener implements ActionBar.OnNavigationListener {
//        // 得到和SpinnerAdapter里一致的字符数组
//        String[] listNames = getResources().getStringArray(R.array.action_bar_blotters_list_category);
//        @Override
//        public boolean onNavigationItemSelected(int itemPosition, long itemId)
//        {
//            // 生成自定的Fragment
//            Ftest category = new Ftest();
//            FragmentManager manager = getFragmentManager();
//            FragmentTransaction transaction = manager.beginTransaction();
//            // 将Activity中的内容替换成对应选择的Fragment
//            transaction.replace(android.R.id.content, category, listNames[itemPosition]);
//            transaction.commit();
//
//            Toast.makeText(BlottersActivity.this,"selected " + itemPosition + "/" + itemId,Toast.LENGTH_SHORT).show();
//            return true;
//        }
//    }
//    public class Ftest extends Fragment
//    {
//// Fragment对应的标签，当Fragment依附于Activity时得到
//
//        private String tag;
//        @Override
//        public void onAttach(Activity activity)
//        {
//            super.onAttach(activity);
//            tag = getTag();
//        }
//        @Override
//        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
//        {
////  View view = (View) inflater.inflate(R.layout.ftest, container, false);
////  TextView textView=(TextView) view.findViewById(R.id.topView);
////  textView.setText(tag);
//            TextView textView = new TextView(getActivity());
//            textView.setText(tag);
//            return textView;
//        }
//    }
}
